﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeWeb;
using Microsoft.Practices.CompositeWeb.Interfaces;

namespace Locator.Products.Views
{
    public class ProductSearchPresenter : Presenter<IProductSearchView>
    {
        private const string SearchResultsKey = "SearchResults";

        private readonly ISessionStateLocatorService sessionService;

        private List<UserProduct> ProductsSearchResult
        {
            get { return sessionService.GetSessionState()[SearchResultsKey] as List<UserProduct>; }
            set { sessionService.GetSessionState()[SearchResultsKey] = value; }
        }

        private readonly IProductsController controller;

        public ProductSearchPresenter
            (
            [CreateNew] IProductsController controller, 
            [ServiceDependency] ISessionStateLocatorService sessionService
            )
        {
            this.controller = controller;
            this.sessionService = sessionService;
        }

        public override void OnViewLoaded()
        {
            this.View.SetSearchResults(this.ProductsSearchResult);
        }

        public override void OnViewInitialized()
        {
            this.ProductsSearchResult = null;
        }

        public void OnSearchByProductNameClicked()
        {
            List<UserProduct> products = this.controller.FindProductsContainingName(this.View.ProductNameToSearch);
            this.ProductsSearchResult = products;
            this.View.SetSearchResults(this.ProductsSearchResult);
        }

        public void OnProductAddedForUser(Locator.Products.UserProduct product)
        {
            this.controller.AddProductForCurrentUser(product.Id);
            // Update the added store to indicate that it's now used by the user
            this.ProductsSearchResult.Find(p => p.Id == product.Id).UsedByUser = true;
            this.View.SetSearchResults(this.ProductsSearchResult);

        }
    }
}




